package net.ycxinxing.mcpebox;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import cn.bmob.v3.Bmob;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import net.ycxinxing.mcpebox.mcpe.Level;
import net.ycxinxing.mcpebox.mcpe.Player;
import net.ycxinxing.mcpebox.mcpe.MinecraftClient;
import android.app.ProgressDialog;

public class mApp extends Application
{
	public final static int mPid=android.os.Process.myUid();
	public static Application thiz;
	private static ClassLoader cl;
	public static ProgressDialog WaitForStartingGame;
	private static Activity mcActivity;
	public static Activity getmcActivity()
	{
		return mcActivity;
	}
    public static String getAppName(Context context)
    {
        int pid = android.os.Process.myPid(); // Returns the identifier of this process
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List list = activityManager.getRunningAppProcesses();
        Iterator i = list.iterator();
        while (i.hasNext())
        {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try
            {
                if (info.pid == pid)
                {
                    return info.processName;
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return null;
    }
	public mApp()
	{
		thiz = this;
		registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks(){
				@Override
				public void onActivityCreated(final Activity activity, Bundle p2)
				{
					baseActivity.log(activity.getClass().toString() + "已启动");
                    if (activity.getClass().toString().equals("class net.ycxinxing.mcpebox.McHelper.MainActivity"))
                    {
                        baseActivity.log("mc启动!");
						mcActivity = activity;
                        if (!activity.getIntent().getBooleanExtra("safemode", false))
                        {
							WaitForStartingGame=new ProgressDialog(activity);
							WaitForStartingGame.setCancelable(false);
							WaitForStartingGame.setMessage("引导Minecraftpe成功，正在等待启动...\n这可能需要几分钟的时间");
							WaitForStartingGame.show();
                            System.load(activity.getIntent().getStringExtra("libpath"));
							for (File path:new File("/data/data/" + getPackageName() + "/addons/").listFiles())
							{
								try
								{
									System.load(path.toString());
								}
								catch (Exception e)
								{
									mDialog dlg=new mDialog(activity){
										@Override
										public void onButtonClick(int i)
										{
											// TODO: Implement this method
										}
									};
									dlg.setTitle("加载" + path.toString() + "时出错");
									dlg.setMsg(e.toString());
									dlg.setButton3("忽略");
									dlg.show();
								}
							}
							NativeCallBack.registerClasses(Level.class,Player.class,MinecraftClient.class);
                            Runnable r=new Runnable(){
                                @Override
                                public void run()
                                {
                                    XFC.showXFC(activity);
                                    // TODO: Implement this method
                                }
                            };
                            new Handler().postDelayed(r, 500);
                        }
						else
						{
                            AlertDialog.Builder ab=new AlertDialog.Builder(activity);
							ab.setMessage("注意，您当前处于安全模式。任何插件均不会被加载，您也不可以使用悬浮窗功能。\n这个模式可能是您手动开启的，也可能因为某些漏洞崩溃而自动开启的，请勿在本模式进入重要存档，以免引发意外。");
							ab.setTitle("安全模式");
							ab.setCancelable(false);
							ab.setPositiveButton("确认", null);
							ab.show();
                        }
                    }
					// TODO: Implement this method
				}

				@Override
				public void onActivityStarted(Activity p1)
				{
					// TODO: Implement this method
				}

				@Override
				public void onActivityResumed(Activity p1)
				{
					// TODO: Implement this method
				}

				@Override
				public void onActivityPaused(Activity p1)
				{
					// TODO: Implement this method
				}

				@Override
				public void onActivityStopped(Activity activity)
				{
					if (activity.getClass().toString().equals("class net.ycxinxing.mcpebox.McHelper.MainActivity"))
                    {
						mcActivity = null;
						System.exit(0);
					}
					// TODO: Implement this method
				}

				@Override
				public void onActivitySaveInstanceState(Activity p1, Bundle p2)
				{
					// TODO: Implement this method
				}

				@Override
				public void onActivityDestroyed(Activity p1)
				{
					// TODO: Implement this method
				}
			});
	}
	@Override
	public void onCreate()
	{
		// TODO: Implement this method
		super.onCreate();
        baseActivity.log("进程:" + getAppName(this) + "已启动");
		ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));
		CrashHandler catchHandler = CrashHandler.getInstance();  
        catchHandler.init(getApplicationContext());  
		cl = this.getClassLoader();
        if (getAppName(this).equals("net.ycxinxing.mcpebox.Pro:net.ycxinxing.process.launcher"))
        {
            baseActivity.log(getClassLoader().toString());
        }
		else
		{
			Bmob.initialize(this, "ad1bd5f3604c0a7b441c83341416defa");
		}
	}
	public static ClassLoader getMyClassLoader()
	{
		return cl;
	}

	@Override
	public AssetManager getAssets()
	{
		if (getAppName(this).equals("net.ycxinxing.mcpebox.Pro:net.ycxinxing.process.launcher"))
        {
            try
			{
				AssetManager am=null;
				Class clazz=getmcActivity().getClassLoader().loadClass("net.ycxinxing.mcpebox.McHelper.MainActivity");
				Field field = clazz.getDeclaredField("am");
				field.setAccessible(true);
				am = (AssetManager)field.get(clazz);
				return am;
			}
			catch (Exception e)
			{
				e.printStackTrace();
				return null;
			}
        }
		else
		{
			// TODO: Implement this method
			return super.getAssets();
		}
	}

}
